package org.nashua.toughtechs151.dash;

import com.sun.squawk.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.TimerTask;
import javax.microedition.io.Connector;
import javax.microedition.io.SocketConnection;

public class ClientConnection extends Connection {
	private SocketConnection sock;
        private InputStreamReader reader;
	private BufferedWriter writer;
	public ClientConnection(String host, int port, ConnectionListener cl) throws Exception {
		super();
		if (cl!=null) setConnectionListener(cl);
		final Connection con = this;
		sock = (SocketConnection) Connector.open("socket://"+host+":"+port);
                reader = new InputStreamReader(sock.openDataInputStream());
		writer = new BufferedWriter(new OutputStreamWriter(sock.openOutputStream()));
		t.schedule(new TimerTask(){
                    public void run() {
                        while (true) {
                            /* Check For Data And Remove Old Connections */
                            try {
                                if (reader.ready()) {
                                    char[] buffer = new char[24];
                                    reader.read(buffer);
                                    String stri = "";
                                    for (int i=0;i<buffer.length;i++) stri+=buffer[i]=='\0'?"":""+buffer[i];
                                    if (stri!=null) con.onDataRecieved(stri);
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
		},1);
		onConnect();
	}
	public void sendData(String str){
            try {
                writer.write(str);
                writer.newLine();
                writer.flush();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
	}
	public void disconnect() {
            try {
                sock.close();
            } catch (IOException e) {
            }
	}
}
